package com.jinlia.show.modules.openservice.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class WebSocketSessionManager {
    /**
     * 保存连接 session 的地方
     */
    public static ConcurrentHashMap<String, ChatWebSocketSession> SESSION_POOL = new ConcurrentHashMap<>();

    /**
     * 添加 session
     *
     * @param userId
     */
    public static void add(String userId, WebSocketSession session) {
        if (SESSION_POOL.containsKey(userId)) {
            removeAndClose(userId);
        }
        // 添加 session
        SESSION_POOL.put(userId, new ChatWebSocketSession(session,userId));
    }


    /**
     * 删除并同步关闭连接
     *
     * @param key
     */
    public static void removeAndClose(String key) {
        if (!SESSION_POOL.containsKey(key)) {
            //用户已被挤掉
            log.info("用户({})已被挤掉!!!",key);
            return;
        }
        WebSocketSession session = SESSION_POOL.remove(key).getWebSocketSession();
        if (session != null) {
            try {
                // 关闭连接
                session.close();
            } catch (IOException e) {
                // todo: 关闭出现异常处理,添加错误处理逻辑
                e.printStackTrace();
            }
        }
    }

    public static class ChatWebSocketSession {
        private WebSocketSession webSocketSession;
        private String userId;
        public ChatWebSocketSession(WebSocketSession webSocketSession,String userId) {
            this.webSocketSession = webSocketSession;
            this.userId = userId;
        }

        public WebSocketSession getWebSocketSession() {
            return webSocketSession;
        }

    }
}
